/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/12/13
 */

import React from 'react';
import { Tree, Divider, Input } from 'antd';
import styles from './Pane.less';
import PropTypes from 'prop-types';
import { arrayToTree } from 'utils';
import CreateRoleForm from './CreateRoleForm';
import UserSelectTransfer from './UserSelectTransfer';

const TreeNode = Tree.TreeNode;
const Search = Input.Search;

export default class RolePane extends React.Component {
  static propTypes = {
    organization: PropTypes.object.isRequired,
    organizationRole: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired,
  };

  constructor (props) {
    super(props);
    this.state = {
      selectedRows: [],
      unSelectedRows: [],
      createFormVisible: false,
    };
  }

  /**
   * 选择角色
   */
  _handleSelectRole = (value) => {
    // 设置角色
    const { dispatch, organizationRole: { roles } } = this.props;
    const currentRoleID = value[0];
    if (currentRoleID) {
      const role = roles.find(_ => {
        return _.ID === currentRoleID;
      });

      if (role.GroupID) {
        // console.log('将要更改的部门', value);
        dispatch({
          type: 'organizationRole/changeCurrentRole',
          payload: {
            role,
          },
        });
      }
    }
  }

  /**
   * 将用户加入当前角色
   */
  _handleAddToRole = (users) => {
    const { dispatch } = this.props;
    if (!Array.isArray(users)) {
      users = Object.values(users);
    }
    // console.log(Array.isArray(Object.values(users)), 'isArray', Object.values(users));
    dispatch({
      type: 'organizationRole/addUserToRole',
      payload: {
        users, 
      },
    });
  }

  /**
   * 将用户从当前部门移除
   */
  _handleRemoveFromRole = (users) => {
    const { dispatch } = this.props;
    if (!Array.isArray(users)) {
      users = Object.values(users);
    }
    dispatch({
      type: 'organizationRole/removeUserFromRole',
      payload: {
        users,
      },
    });
  }

  _toggleCreateFormModal = () => {
    this.setState({
      createFormVisible: !this.state.createFormVisible,
    });
  }

  _handleCreateFormCancel = () => {
    this._toggleCreateFormModal();
  }

  _handleCreateFormSubmit = (values) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organizationRole/createRoleOrGroup',
      payload: {
        postData: values, 
      },
    });
  }

  _generateRolesTree = () => {
    const { roles } = this.props.organizationRole;
    const deptTree = arrayToTree(roles, 'ID', 'GroupID', 'children');
    // let firstDept = null;
    const toTreesComponent = (_roles) => {
      return _roles.map(role => {
        if (role.children && Array.isArray(role.children)) {
          return (
            <TreeNode title={role.Name || role.GroupName} key={role.ID} >
              {toTreesComponent(role.children)}
            </TreeNode>
          );
        }
        return <TreeNode title={role.GroupName || role.Name} key={role.ID} />;
      });
    };

    return (
      <Tree
        showLine
        onSelect={this._handleSelectRole}
        defaultExpandedKeys={['0-0-0']}
      >
        {toTreesComponent(deptTree)}
      </Tree>
    );
  }

  __loadAllUsers = (page) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organizationRole/loadAllUsers',
      payload: {
        isLoad: true,
        page,
        limit: 10,
      },
    });
  };

  render () {
    const { organization, organizationRole } = this.props;

    return (
      <div className={styles.paneContainer} >
        {/* <CreateForm 
          visible={this.state.createFormVisible}
          depts={this.props.organizationRole.departments}
          handleCancel={this._handleCreateFormCancel}
          handleSubmit={this._handleCreateFormSubmit}
        /> */}
        <CreateRoleForm
          visible={this.state.createFormVisible}
          roles={this.props.organizationRole.roles}
          handleCancel={this._handleCreateFormCancel}
          handleSubmit={this._handleCreateFormSubmit}
        />
        <div className={styles.card} >
          <div className={styles.header}>
            <div className={styles.title}>
              <h3>{organization ? organization.Name : '-'}</h3>
            </div>
            <div className={styles.btn}>
              <a onClick={this._toggleCreateFormModal}>新增角色</a>
            </div>
          </div>
          <div className={styles.content} >
            <div className={styles.search}>
              <Search
                placeholder="搜索"
                onSearch={value => console.log(value)}
              />
            </div>
            {this._generateRolesTree()}
          </div>
        </div>
        <Divider type="vertical" dashed={false} className={styles.divider} />
        <UserSelectTransfer
          title={organizationRole.currentRole && organizationRole.currentRole.Name}
          folderLength={(organizationRole.roles || []).length}
          selectedRows={organizationRole.selectedUsers}
          allRows={organizationRole.allUsers}
          hasMore={false}
          onLoadRightList={this.__loadAllUsers}
          onAdd={users => this._handleAddToRole(users)}
          onRemove={users => this._handleRemoveFromRole(users)}
        />
      </div>
    );
  }
}
